//
// Created by luosong on 15/8/27.
// Copyright (c) 2015 CHANJET. All rights reserved.
//

#import "CSPNetworkingRequest.h"


#pragma mark - CSPRequest

@interface CSPNetworkingRequest ()

@property (nonatomic, strong) NSURLSessionTask *task;
@property (nonatomic, assign, getter = isCancelled) BOOL cancelled;

@end

@implementation CSPNetworkingRequest

- (void)assignProperties:(CSPRequestConfig *)config {
    if (!self.baseURL) {
        self.baseURL = config.baseURL;
    }

    if (!self.URLString) {
        self.URLString = config.URLString;
    }

    if (!self.HTTPMethod) {
        self.HTTPMethod = config.HTTPMethod;
    }

    if (config.headers) {
        NSMutableDictionary *mutableCopy = [config.headers mutableCopy];
        [self.headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            mutableCopy[key] = obj;
        }];
        self.headers = mutableCopy;
    }

    if (config.requestInterceptors) {
        self.requestInterceptors = config.requestInterceptors;
    }

    if (config.responseInterceptors) {
        self.responseInterceptors = config.responseInterceptors;
    }

    if (!self.retryHandler) {
        self.retryHandler = config.retryHandler;
    }
}
- (void)setTask:(NSURLSessionTask *)task {
    @synchronized(self) {
        if (!_cancelled) {
            _task = task;
        } else {
            _task = nil;
        }
    }
}

- (BOOL)isCancelled {
    @synchronized(self) {
        return _cancelled;
    }
}

- (void)cancel {
    @synchronized(self) {
        if (!_cancelled) {
            _cancelled = YES;
//            [self.task cancel];
        }
    }
}

- (void)pause {
    @synchronized(self) {
//        [self.task cancel];
    }
}

@end